﻿@model IEnumerable<TeamCityMonitor.Models.ProjectModel>
@{
    ViewBag.Title = "TeamCity Monitor";
}

<script type="text/javascript">
    
    var configuredToShowAtOnce = @ViewBag.ConfiguredNoOfFeedsToShowAtOnce;
    var feedsToShowAtOnce = @ViewBag.FeedsToShowAtOnce;
    var feedDelay = @ViewBag.FeedDelay;
    var scaleToWidth = @ViewBag.ScaleToWidth;
    var feedIndex = 0;

    var viewModel = ko.mapping.fromJS([],
    {
            key: function(data) {
                return ko.utils.unwrapObservable(data.BuildConfig);
            },
            create: function (options) {
                return new newConfigModel(options.data);
            }
    });

    var newConfigModel = function (data) {
            ko.mapping.fromJS(data, {}, this);
            
            this.DisplayBuildNumber = ko.dependentObservable(function() { return GetBuildNumber(this); }.bind(this));
            this.DisplayTitle = ko.dependentObservable(function() { return GetDisplayTitle(this); }.bind(this));
            this.StatusClass = ko.dependentObservable(function () { return GetStatusClass(this); }.bind(this));
            this.DisplayRunning = ko.dependentObservable(function() { return GetDisplayRunning(this); }.bind(this));
        
            this.FeedIndexShadow = "";
            this.FeedIndex = ko.dependentObservable(function() { return GetNewFeedIndex(this); }.bind(this));
        };
    
    $(document).ready(function () {
        
        function loadConfigurations() {
            var url = "/Home/GetProjects/";
            $.ajax({
                url: url,
                success: function(response) {

                    if (response.success) 
                    {
                        ko.mapping.fromJS(response.results, viewModel);

                        $("#lastRefresh").text("Last Refresh : " + GetDateTime());
                        $("#fetchfailed").hide("slow");
                        $("#loading").remove();
                    } 
                    else 
                    {
                        ShowError(response.message);
                    }
                },
                error: function(response) {

                    ShowError("");
                }
            });
        }
        
        function checkForRedirect() {
            var url = "/Home/ShouldRedirect/";
            $.ajax({
                url: url,
                success: function(response) {

                    if (response.success) 
                    {
                        window.location = response.redirect;
                    } 
                }
            });
        }

        ko.applyBindings(viewModel);

        loadConfigurations();
        
        window.setInterval(function () { loadConfigurations(); }, 5000);
        
        window.setInterval(function () { checkForRedirect(); }, 2000);
        
        $(".userProfile").animate({ width: scaleToWidth });
    });
    
    function GetStatusClass (project)  {
        if(project.IsRunning() == true) {
            return "projectItem running".toString();
        } 
                
        return "projectItem ".concat(String(project.LastBuildStatus()).toLowerCase()).toString();
    }

    function GetDisplayTitle (project)  {
        /*if(project.IsRunning() == true) {
            return project.Title() + " (Running)";
        }*/
                
        return project.Title();
    }

    function GetDisplayRunning (project)  {
        if(project.IsRunning() == true) {
            return "(Running)";
        }
                
        return "";
    }
    function GetBuildNumber (project)  {
        var statusText = project.LastBuildStatusText();

        if(statusText == null) {
            statusText = "";
        }

        if(statusText != null && statusText != "") {
            statusText = ", " + statusText;
        }
        
        if(project.BuildNumber() != "" && project.BuildNumber() != null) {
            return "Build: " + project.BuildNumber() + statusText;
        }
                
        return "";
    }
    
    function GetNewFeedIndex (project)  {
        
        if(project.FeedIndexShadow != "") {
            return project.FeedIndexShadow;
        }

        var possibleFeedIndexes = [];
        for(var i = 0; i < viewModel().length + 1; i++) {
            possibleFeedIndexes.push("feed" + i);
        }

        for(var j = 0; j < viewModel().length; j++) {

            var index = possibleFeedIndexes.indexOf(viewModel()[j].FeedIndexShadow);
            
            if(index > -1) 
            {
                possibleFeedIndexes.splice(index,1);
            }
        }

        project.FeedIndexShadow = possibleFeedIndexes[0];

        return project.FeedIndexShadow;
    }
    
    function GetDateTime () {
        var currentTime = new Date();
        var month = currentTime.getMonth() + 1;
        var day = currentTime.getDate();
        var year = currentTime.getFullYear();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        return new String().concat(day, "/", month, "/", year, " ", hours, ":", minutes);
    }
    
    function ShowError(errorMessage) {

        $("#loading").remove();
        $("#fetchfailed").text("WARNING: Failed to retrieve projects ... " + errorMessage);
        $("#fetchfailed").show("slow");
    }
    
    function move(feedIndex) {
        return function () {
            $(feedIndex).remove().css('display', 'none').prependTo('#feeds');
        };
    }
    
    function shift() {

        removeDeadFeeds();

        var count = viewModel().length; 
        if (count > feedsToShowAtOnce) {

            var toShow = (feedIndex + feedsToShowAtOnce) % count;
            var indexToShow = "#" + viewModel()[toShow].FeedIndexShadow;
            var indexToHide = "#" + viewModel()[feedIndex].FeedIndexShadow;
            
            $(indexToShow).slideDown(1000, move(indexToHide)); //Display

            $(indexToHide).slideUp(1000, move(indexToHide)); //Hide
            
            feedIndex = (feedIndex + 1) % count;
        } 
        else 
        {
            ko.utils.arrayForEach(viewModel(), function(model) {
                $("#" + model.FeedIndexShadow).removeAttr("style");
            });
            
            feedIndex = 0;
        }
            
        setTimeout('shift()', feedDelay);
    }
    
    function removeDeadFeeds() {
        var currentIds = [];

        $('[id^="feed"]').each(function() {
            if(this.id != "feeds") {
                currentIds.push(this.id);
            }
        });
        
        ko.utils.arrayForEach(viewModel(), function(model) {
            var index = currentIds.indexOf(model.FeedIndexShadow);
            if(index > -1) 
            {
                currentIds.splice(index,1);
            }            
        });        
        
        for(var i  = 0; i < currentIds.length; i++) {
            $("#" + currentIds[i]).remove();
        }
    }
    
    $(document).ready(function () {
        setTimeout('shift()', feedDelay);
    });

</script>

<div id="fetchfailed" class="warning">
</div>

<div id="loading" class="loading">
    <img src="../../Content/ajax-loader.gif" alt="Loading..." />
</div>

<div class="configContainer home" id="feeds"  data-bind="foreach: viewModel">

    <div data-bind="attr: { 'class': StatusClass, 'id': FeedIndex }" style="display: none">
        <div class="configRow">
            <div class="configContentLeft">
                <img class="userPicture" data-bind='attr: { src: LastChangeUserPictureUrl }' />
            </div>

            <div class="configContentRight">
                <h2 class="buildStatus" data-bind="text: DisplayRunning"></h2>
            </div>
            
            <div class="configContentMiddle">
                <h2 class="displayTitle" data-bind="text: DisplayTitle"/>
                <h2 class="displaySubTitle" data-bind="text: SubTitle"/>
                <h2 class="changeUser" data-bind="text: LastChangeUser"></h2>
                <h2 class="changeComment" data-bind="text: LastChangeComment"></h2>
            </div>

        </div>
    </div>
</div>

<div id="foot">
    <h3 id="lastRefresh">
    </h3>
</div>
